<?php

namespace app\admin\model;

use app\admin\lib\exception\BaseException;
use think\Model;

class Common extends Model
{
    protected $name = 'users';
    protected $hidden = ['password', 'password_confirm', 'role', 'status', 'update_time'];
    /**
     * 管理员新增钩子方法
     */
    protected static function onBeforeInsert($data)
    {
        // 检查用户名是否已存在
        $usernameExists = self::where('username', trim($data->username))->find();
        if ($usernameExists) {
            throw new BaseException([
                'code' => 400,
                'message' => '用户名已存在',
                'errorCode' => 60003
            ]);
        }

        $emailExists = self::where('email', trim($data->email))->find();
        if ($emailExists) {
            throw new BaseException([
                'code' => 400,
                'message' => '邮箱已存在',
                'errorCode' => 60005
            ]);
        }

        $phoneExists = self::where('phone', trim($data->phone))->find();
        if ($phoneExists) {
            throw new BaseException([
                'code' => 400,
                'message' => '手机号已存在',
                'errorCode' => 60006 // 不同错误码
            ]);
        }

        // 密码加密处理
        $data->password = password_hash(trim($data->password), PASSWORD_DEFAULT);

        // 头像字段：允许为空；有传递则清理空白
        if (isset($data->avatar)) {
            $data->avatar = trim((string)$data->avatar);
        }
    }
}